import { Button, Drawer, Input, Layout, message, Modal, Space, Dropdown, MenuProps } from 'antd';
import { Content, Header } from 'antd/es/layout/layout';
import Sider from 'antd/es/layout/Sider';
import { useEffect, useRef, useState } from 'react';
import { SvgIcon } from '@/components/icon';
import Back from '@/components/router/Back';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useRouter } from '@/router/hooks';
import { useUserInfo } from '@/store/userStore';
import RouterMenu from '../components/menus/RouterMenu';
import './styles/role.scss';
import RoleManageContextProvider, { RoleManageContext } from './context';
import { Role, RoleManageEvent } from '@/types/role';
import RoleList from './components/RoleList';
import RoleDetail from './components/role-detail';
import { EditOutlined, FileTextOutlined, PlusOutlined } from '@ant-design/icons';
import NewRoleModal from './components/NewRoleModal';
import { useRoleManageActions, useRoleManage, useRoleState } from '@/store/roleManageStore';
import { useContextSelector } from 'use-context-selector';
import DeleteConfirmModal from '../datasets/components/DeleteConfirmModal';
import roleService from '@/api/services/roleService';
import { findNodeById, findParentIdArray, findParentNameArray } from '@/utils/tree';
import EditCdtMetadataModal from './components/EditCdtMetadataModal';
import { useManagePage } from '@/store/configStore';
import { useSize } from 'ahooks';
import usePermission from '@/hooks/event/usePermission';
import { useDatasetStore } from '@/store/datasetStore';
import { GetRoleRes } from '@/common';

interface Props {
  version?: string;
  rolesList?: GetRoleRes[];
}

function RoleManage({ version, rolesList }: Props) {
  const router = useRouter();
  const [mobileApiVisible, setMobileApiVisible] = useState(false);
  const [newRoleVisible, setNewRoleVisible] = useState(false);
  const [editCdtMdModalVisible, setEditCdtMdModalVisible] = useState(false);
  const { isPc } = useWindowWidth();
  const { isAdmin, isPermit, isInManager } = usePermission();
  const [delModalVisible, setDelModalVisible] = useState(false);
  const { event$ } = useContextSelector(RoleManageContext, (s) => s);
  const [editRole, setEditRole] = useState<Role | undefined>(undefined);
  const { getRoles, setSelectedRole, getCdtMetaData } = useRoleManageActions();
  const [loading, setLoading] = useState(false);
  const { roles } = useRoleState();
  const { selectedRole } = useRoleManage();
  const managePage = useManagePage();
  const ref = useRef<HTMLDivElement>(null);
  const size = useSize(ref);

  const { allDatasets, loadAllDatasets } = useDatasetStore();

  const handleItemClicked = (item: Role | undefined) => {
    setSelectedRole(item);
  };

  const closeNewRoleModal = () => {
    setEditRole(undefined);
    setNewRoleVisible(false);
  };

  const handleDeleteConfirm = async () => {
    try {
      if (!selectedRole) {
        setDelModalVisible(false);
        return;
      }
      await roleService.delRole(selectedRole.id);
      message.success(`删除角色 ${selectedRole.name} 成功！`);
      // 选中上一级菜单
      const array = findParentIdArray(roles, selectedRole.id);
      if (array) {
        const role = findNodeById(roles, array[array.length - 1] ?? '');
        setSelectedRole(role);
      }
      getRoles();
      setDelModalVisible(false);
    } catch (error) {
      console.error(error);
    }
  };

  event$?.useSubscription((val) => {
    switch (val) {
      case RoleManageEvent.EDITCURRENTROLE:
        setEditRole(selectedRole);
        setNewRoleVisible(true);
        break;
      case RoleManageEvent.DELCURRENTROLE:
        setDelModalVisible(true);
        break;
      default:
        break;
    }
  });

  const initData = async () => {
    try {
      setLoading(true);
      await getRoles();
      await getCdtMetaData();
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    initData();
  }, []);

  // useEffect(() => {
  //   loadAllDatasets({
  //     parentId: null,
  //   });
  // }, [newRoleVisible]);

  useEffect(() => {
    if (!isPc) {
      setMobileApiVisible(selectedRole != undefined);
    }
  }, [selectedRole]);

  return (
    <Layout ref={ref} className="h-full" style={{ background: '#EDEFF7' }}>
      <Header style={{ background: '#EDEFF7', padding: 0 }}>
        <div className="flex flex-nowrap items-center justify-between">
          <div className="flex w-full">
            {!version && !isInManager && (
              <Back
                title="返回"
                onClick={() => {
                  router.push(managePage);
                }}
              />
            )}
            {/* <div
              style={{
                width: '2px',
                height: '20px',
                backgroundColor: '#8b8282',
                marginLeft: '20px',
                marginTop: '25px',
              }}
            />
            <RouterMenu /> */}
            {
              <Space className="ml-auto mr-5">
                <>
                  {!version && selectedRole && (
                    <Button
                      type="text"
                      icon={<PlusOutlined />}
                      onClick={() => {
                        setNewRoleVisible(true);
                      }}
                    >
                      {isPc ? '新增角色' : ''}
                    </Button>
                  )}
                  {isAdmin && (
                    <Button
                      type="text"
                      icon={<FileTextOutlined />}
                      onClick={() => {
                        setEditCdtMdModalVisible(true);
                      }}
                    >
                      {isPc ? '关键字管理' : ''}
                    </Button>
                  )}
                </>
              </Space>
            }
          </div>
        </div>
      </Header>
      <Layout style={{ background: '#EDEFF7' }}>
        <Sider
          style={{ background: 'transparent' }}
          width={isPc ? '300px' : '100%'}
          className="flex flex-col overflow-hidden"
        >
          <RoleList
            loading={loading}
            // datas={roles}
            datas={rolesList !== undefined ? rolesList : roles}
            selectedItem={selectedRole}
            onItemClicked={handleItemClicked}
            version={version}
          />
        </Sider>

        <Content
          className="relative ml-2 mr-2 rounded-xl"
          style={{
            overflowY: 'auto',
            overflowX: 'hidden',
          }}
        >
          <RoleDetail
            loading={loading}
            isAdmin={isAdmin}
            isPermit={isPermit}
            onItemClicked={handleItemClicked}
            version={version}
          />
        </Content>
      </Layout>

      <EditCdtMetadataModal
        parentSize={size}
        visible={editCdtMdModalVisible}
        onCancel={() => {
          setEditCdtMdModalVisible(false);
        }}
      />

      <NewRoleModal
        visible={newRoleVisible}
        onCancel={closeNewRoleModal}
        initialValues={editRole}
        allDatasets={allDatasets}
        version={version}
      />

      <DeleteConfirmModal
        visible={delModalVisible}
        text={`确定要删除角色 ${selectedRole?.name} 吗？`}
        onCancel={() => {
          setDelModalVisible(false);
        }}
        onConfirm={handleDeleteConfirm}
      />

      <Drawer
        title={
          <span
            style={{
              fontSize: '20px',
              fontWeight: 500,
              color: '#474C5F',
            }}
          >
            角色列表
          </span>
        }
        open={mobileApiVisible}
        onClose={() => {
          setMobileApiVisible(false);
        }}
        width="100%"
        zIndex={100}
        closeIcon={<SvgIcon icon="ic-back" size={24} />}
        className="role-drawer"
      >
        <div className="mt-2 h-full">
          <RoleDetail isAdmin={isAdmin} isPermit={isPermit} onItemClicked={handleItemClicked} />
        </div>
      </Drawer>
    </Layout>
  );
}

function RenderRoleManage({ version, rolesList }: Props) {
  return (
    <RoleManageContextProvider>
      <RoleManage version={version} rolesList={rolesList} />
    </RoleManageContextProvider>
  );
}

export default RenderRoleManage;
